package cn.dz.service.impl;

import cn.dz.dao.UserDao;
import cn.dz.entity.User;
import cn.dz.mapper.UserMapper;
import cn.dz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName UserServiceImpl
 * @package: cn.dz.service.impl
 * @Description TODO
 * @Author dz
 * @Date 2024/12/22 16:29
 * @Version 1.0
 **/
@Service
@Transactional
public class UserServiceImpl implements UserService {


    UserMapper userMapper;
    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void regist(User user) {
        // 根据用户名查询数据库中是否存在该用户
        User userDB = userMapper.findByUserName(user.getUsername());
        if (!ObjectUtils.isEmpty(userDB)) {
            throw new RuntimeException("当前用户名已经被注册");
        }
        userMapper.save(user);
    }

    @Override
    public User login(String username, String password) {
        //1.根据用户名查询用户
        User user = userMapper.findByUserName(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户名不正确");
        }
        // 比较密码
        String passwordSecret = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if(!user.getPassword().equals(passwordSecret)) {
            throw new RuntimeException("密码输入错误");
        }
        return user;
    }
}
